<template>
  <div class="answer-form">
    <VueDraggableNext v-model="list" @start="onStart" @end="onEnd" handle=".handle" animation="200"
      ghostClass="answer-form__ghost" chosenClass="answer-form__chosen">
      <transition-group>
        <div class="answer-form__item" v-for="(item, index) in list" :key="`${item.id}_${index}`"
          :class="{ 'answer-form__no': index === 0 }">
          <span v-if="item.optionLabel" class="answer-form__label">{{ item.optionLabel
            }}、</span>
          <el-input v-model="item.content" placeholder="请输入题目" />
          <img class="answer-form__handle handle" :src="questionDr" />
          <el-checkbox v-model="item.rightState" size="large" @change="changeCheckbox(item)" />
          <el-icon size="17" @click="removeItem(item, index)">
            <Close />
          </el-icon>
        </div>
      </transition-group>
    </VueDraggableNext>
  </div>
</template>

<script setup>
import { VueDraggableNext } from "vue-draggable-next";
import { questionDr } from "../assets/images";
const emits = defineEmits(['update'])
const props = defineProps({
  answer: {
    type: Array,
    required: true,
    default: () => [],
  },
  questionType: {
    type: String,
    default: '1',
  }
});
let list = ref([]);
watch(() => props.answer, (value) => {
  console.log("🚀 ~ props.answer:", props.answer)
  list.value = value
  if (value.length === 0) {
    list.value.push({
      content: "",
      rightState: false,
      optionLabel: "A",
      id: new Date().getTime(),
    })
  }
}, { immediate: true });

function removeItem(row, index) {
  list.value.splice(index, 1);
  onEnd();
}
function onStart() {
  console.log("🚀 ~ onStart ~ onStart:")
}
function onEnd() {
  const arr = [];
  for (let i = 0; i < list.value.length; i++) {
    const item = list.value[i];
    arr.push({
      ...item,
      optionLabel: String.fromCharCode("A".charCodeAt() + i),
    });
  }
  // list.value = arr;
  emits('update', arr)
  // list.value.forEach((row, index)=>{
  //   row.optionLabel = String.fromCharCode("A".charCodeAt() + index)
  // }) 
}
function changeCheckbox(item) {
  list.value.forEach(row=>{
    if (item.content === row.content){
      row.rightState = true
    } else {
      row.rightState = false
    }
  }) 
}

function changeType() {
  list.value = [];
  addItem();
}

function addItem() {
  const currentLabel = list.value.length || 0;
  list.value.push({
    content: "",
    rightState: false,
    optionLabel: String.fromCharCode("A".charCodeAt() + currentLabel),
    id: new Date().getTime(),
  });
}

const getQuestionAnswerList = () => {
  return list.value;
};

defineExpose({
  changeType,
  addItem,
  getQuestionAnswerList,
});
</script>
<style lang="scss" scoped>
@import './AnswerForm.scss'
</style>
